package parser3;

import org.antlr.runtime.Token;

import java.util.List;

/**
 * The class represents a view into an array of tokens.  It is equal to another chunk when all of the tokens
 * match.
 *
 * @author brianegge
 */
public class Chunk {
    private final List<Token> tokens;
    private final TokenComparator comparator;
    private final int index;
    private final short size;

    public Chunk(List<Token> tokens, TokenComparator comparator, int index, short size) {
        this.tokens = tokens;
        this.comparator = comparator;
        this.index = index;
        this.size = size;
    }

    public int hashCode() {
        int code = 0;
        for (int i = index; i < index + size; i++) {
            final int type = tokens.get(i).getType();
            code ^= type;
            code <<= 1;
            if (!comparator.equate(type)) {
                code ^= tokens.get(i).getText().hashCode();
            }
        }
        return code;
    }


    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Chunk chunk = (Chunk) o;
        return equals(chunk);
    }

    public boolean equals(Chunk chunk) {
        for (int i = 0; i < size; i++) {
            Token left = get(i);
            Token right = chunk.get(i);
            if (comparator.compare(left, right) != 0) {
                return false;
            }
        }
        return true;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = index; i < index + size; i++) {
            sb.append(tokens.get(i)).append(" ");
        }
        return sb.toString();
    }

    public Token get(int offset) {
        assert offset < size;
        return tokens.get(index + offset);
    }
}
